package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/vueadmin/pkg/jwt"
	e "github.com/vueadmin/utils/exception"
)

// 解析jwt
func JwtVerify(app string) gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("Authorization")
		if token == "" {
			panic(e.ValidateError("token不能为空"))
		}
		data, err := jwt.NewJwt(app).ParseToken(token)
		if err != nil {
			if err == jwt.TokenExpired {
				panic(e.ValidateWithCodeError{Msg: "token过期", Code: 101})
			} else {
				panic(e.ValidateWithCodeError{Msg: "token解析错误", Code: 102})
			}
		}
		c.Set("claims", data)
		c.Next()
	}
}
